"""
transcript.py

This file is part of a program that implements a Software-Defined Radio.

Copyright (C) 2014 by G3UKB Bob Cowdery

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

The authors can be reached by email at:

	bob@bobcowdery.plus.com

"""

# Python imports
import sys, os
from multiprocessing import Process
from multiprocessing import Queue
import logging
from time import sleep
from PyQt4 import QtCore, QtGui

# Application imports
from common.defs import *
import transcript.logger as logger
import transcript.transcript_window as transcript_window

"""
The transcript manages all application messages.
"""

# The one and only q
g_transcript_q = None
g_transcript_window = None
g_logger = None

def transcript_init():
	""" Initialise the transcript server """
	
	# Create a new process to manage the transcript
	g_transcript_q = Queue()
	server = Process(target=transcript_server, args=(g_transcript_q, ))
	server.start()
	return g_transcript_q

def transcript_close(transcript_q):
	""" Close the transcript server """
	
	transcript_q.put((CLOSE, None, None, None))

# This runs in the context of a new process
def transcript_server(transcript_q):
	
	"""
	A transcript server has the following responsibilities
		1. Accept messages from multiple producers on the given Queue
		2. Output important messages to the transcript window.
		3. Log all messages using the logging module with time cyclic logging
	
	The message format is :
		(type, severity, source, msg)
		Where type is one of:
			CLOSE	- 	terminate the transcript
			LOG		- 	output to log only
			TRANS	-	output to transcript only
			BOTH	-	output to both
	
	Arguments:
		g_transcript_q	--	message q
		
	"""
	global g_transcript_q
	global g_transcript_window
	
	g_transcript_q = transcript_q
	
	# Create a transcript window
	# The QApplication 
	qt_app = QtGui.QApplication(sys.argv)
	# Create the transcript window
	g_transcript_window = transcript_window.TranscriptWindow()
	# Call process every 100ms
	timer = QtCore.QTimer()
	timer.timeout.connect(process)
	timer.start(100)
	# Start GUI processing event loop
	return(qt_app.exec_())
		
def process():
	
	global g_logger
	global g_transcript_q
	global g_transcript_window
	
	# Set up the local logging environment
	if g_logger == None:
		g_logger = logger.Logger()
		l = logging.getLogger('sdr_script')
		l.log(logging.INFO, 'Logging started')
	
	# Wait for messages
	while not g_transcript_q.empty():
		try:
			obj = g_transcript_q.get()
			msg_type, severity, source, msg = obj
			if msg_type == CLOSE:
				g_transcript_window.close()
				return
			elif msg_type == HIDE:
				g_transcript_window.hide()
			elif msg_type == SHOW:
				g_transcript_window.show()
			elif msg_type == LOG:
				l = logging.getLogger('sdr_script.%s' % (source))
				l.log(severity, msg)
			elif msg_type == TRANS:
				g_transcript_window.add_message(msg)
			elif msg_type == BOTH:
				l = logging.getLogger('sdr_script.%s' % (source))
				l.log(logging.INFO, msg)
				g_transcript_window.add_message(severity, source, msg)
				
		except Exception as e:
			# Oops, what now
			# Just ignore for the moment
			return
		